package common;

import java.io.File;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

//This class has a method which helps parsing Test Data XML.
public class ReadTestDataXML {

	public HashMap<String, String> parseTestDataXML(String xmlFileName, String strRequiredName) {
     HashMap<String,String> map = new HashMap<String,String>();

     try {
       //getting calling class name
			 //For now I am assuming that file name is passed
		
			 // Open the testdata xml file
			 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			 DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			 Document doc = docBuilder.parse (new File(xmlFileName));

			 // normalize text representation
			doc.getDocumentElement ().normalize ();

			//find the root with the filename string
			String temp [] = null;
	    temp = xmlFileName.split("\\.xml");
	            
	    String temp2 [] = null;
      String pathname = temp[0];
	    System.out.println("Pathname = " + pathname);
	    temp2 = pathname.split("testdata");
	            
	    int i = temp2.length;
	            
	    String rootName = temp2[i-1].substring(1);
	    System.out.println("RootName =" + rootName);
	    
			//find 1st child, match it with required childname
	    NodeList nList = doc.getElementsByTagName(rootName);
    	System.out.println("Node list length " + nList.getLength());
    		
      Node nParent = nList.item(0);
            
      NodeList nChildrensList = nParent.getChildNodes();
      int childrenCnt = nChildrensList.getLength();
            
      System.out.println(nChildrensList.getLength());
           
      Node child = nParent.getFirstChild();
      System.out.println("Parent node name: " + nParent.getNodeName());
      System.out.println("First child name: " + child.getNodeName());
            
      for (int cnt = 0; cnt < childrenCnt; cnt++){
        //if matches read the children and set them as key value in map
	            if (child.getNodeName().equalsIgnoreCase(strRequiredName)) {
	             int tCnt = 0; 
	                
	            String TagName = null;
	            String TagValue = null;
	                 
	            NodeList nSubChildList = child.getChildNodes();
	            int nSubChildListCnt = nSubChildList.getLength();
	                 
	            Node subChild = child.getFirstChild();
	                 
	            for (int j = 0; j < nSubChildListCnt; j++) {  
                if (subChild.getNodeType() == Node.ELEMENT_NODE ) {	
                   System.out.println("Tag => " + subChild.getNodeName());
	                 	   
	                 TagName = new String(subChild.getNodeName()); 
	                 
	                 if (subChild.hasChildNodes()) {
                       NodeList nl1 = subChild.getChildNodes();
	                  	 System.out.println("Value => " + nl1.item(0).getNodeValue().trim());
	
	                 	  TagValue = new String(nl1.item(0).getNodeValue().trim());
	                  	 map.put(TagName, TagValue);
	                  }    
	                 tCnt++;
	              } //end of if --   if (child.getNodeType() == Node.ELEMENT_NODE ) {	
                subChild = subChild.getNextSibling();
	            }  //end of for
	            return map;	
	         } //end of             if (child.getNodeName().equalsIgnoreCase(strChildName))
	         else {
	         	//else continue
	           child = child.getNextSibling();
	           System.out.println("Next sibling = " + child.getNodeName());
	         }
        } //end of for
        map.put("empty", "empty");
        return map;
			//if cannot be found give out an error
		
		}catch (SAXParseException err) {
		    
	        System.out.println ("** Parsing error" + ", line " 
	             + err.getLineNumber () + ", uri " + err.getSystemId ());
	        System.out.println(" " + err.getMessage ());
	        map.put("empty", "empty");
            return map;
	        //return null;

	        }catch (SAXException e) {
	        Exception x = e.getException ();
	        ((x == null) ? e : x).printStackTrace ();
	        map.put("empty", "empty");
            return map;
	        //return null;
	        }catch (Throwable t) {
	        t.printStackTrace ();
	        map.put("empty", "empty");
            return map;
	        //return null;
	   }	

	}

}
